﻿using System;
using System.ServiceModel;
using System.ServiceModel.Security;
using GalaSoft.MvvmLight.Messaging;
using LiSAClient.Core;
using LiSAClient.Core.Messages;
using LiSAClient.Core.Models;
using LiSAClient.ServiceProvider;
using log4net;

namespace LiSAClient.WpfClient.Utils
{
    public class ErrorHandler : IServiceExceptionsHandler
    {
        private readonly ILog log;

        public ErrorHandler()
        {
            this.log = LogManager.GetLogger(typeof(ErrorHandler));
            ServiceHandler.Instance.RegisterExceptionsHandler(this);

            if (!AppContext.IsTest)
            {
                AppDomain.CurrentDomain.UnhandledException += (s, e) => this.Handle((Exception)e.ExceptionObject);
            }
        }

        /// <summary>
        /// Handler for a general unhandled exception.
        /// </summary>
        /// <typeparam name="T">The type of exception.</typeparam>
        /// <param name="e">The exception.</param>
        public void Handle<T>(T e) where T : Exception
        {
            string header;
            string msg;
            NotificationType notificationType;

            // Just a way to confirm that the error was because of a wrong login, then we don't want the popup message.
            if (e.GetType() == typeof(MessageSecurityException))
            {
                Messenger.Default.Send(new LoginFailedMessage("Login details were incorrect"));
                return;
            }

            if (e.GetType() == typeof(EndpointNotFoundException))
            {
                msg = "Endpoint exception!";
                header = "Warning";
                notificationType = NotificationType.Warning;
            }
            else
            {
                msg = "An error has occurred";
                header = "Error";
                notificationType = NotificationType.Error;
            }

            this.log.Error(e.Message, e);

            Messenger.Default.Send(new ShowNotificationMessage { Body = msg, Header = header, NotificationType = notificationType });
        }
    }
}